//
//  HZJDownLOadTVCell.m
//  HZ_Beautiful_Music
//
//  Created by dllo on 16/4/7.
//  Copyright © 2016年 ui. All rights reserved.
//

#import "HZJDownLOadTVCell.h"



@interface HZJDownLOadTVCell ()<NSURLSessionDownloadDelegate>


//@property (nonatomic, strong) UILabel *pgLable;
@property (nonatomic, strong) UIProgressView *myPregress;
@property (nonatomic, strong) UIButton *button;

@property (nonatomic, strong) UILabel *title;
@property (nonatomic, strong) UILabel *name;

@property (nonatomic, copy) NSString *urlStr;

/**
 *  下载任务
 */
@property (nonatomic, strong) NSURLSessionDownloadTask* downloadTask;
/**
 *  resumeData记录下载位置
 */
@property (nonatomic, strong) NSData* resumeData;
/**
 *  session
 */
@property (nonatomic, strong) NSURLSession* session;

/**
 *  筛选
 */
@property (nonatomic, copy) NSString *path;
@property (nonatomic, strong) NSFileManager * fileManager;
@property (nonatomic, strong) NSArray * tempFileList;
@property (nonatomic, strong) NSMutableArray *data;

@end

#define FILEPATH [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0]


@implementation HZJDownLOadTVCell

- (void)dealloc {
    
    [[NSNotificationCenter defaultCenter] removeObserver:self];
    
}

- (instancetype)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier {
    self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
    if (self) {

        self.data = [NSMutableArray arrayWithCapacity:0];
        self.button = [UIButton buttonWithType:UIButtonTypeSystem];
        [self.contentView addSubview:_button];
        
        self.myPregress = [[UIProgressView alloc] init];
        [self.contentView addSubview:_myPregress];
        
        self.title = [[UILabel alloc] initWithFrame:CGRectZero];
        [self.contentView addSubview:_title];
        
        self.name = [[UILabel alloc] initWithFrame:CGRectZero];
        [self.contentView addSubview:_name];
        
        self.path = [NSString stringWithFormat:@"%@/music", FILEPATH];
        self.fileManager = [NSFileManager defaultManager];
        self.tempFileList = [[NSArray alloc] initWithArray:[_fileManager contentsOfDirectoryAtPath:_path error:nil]];
        
        for (int i = 0; i < _tempFileList.count; i++) {
            NSString *string = _tempFileList[i];
            if ([[string pathExtension] isEqualToString:@"mp3"]) {
                [_data addObject:_tempFileList[i]];
            }
        }
        
    }
    return self;
}

- (void)layoutSubviews {
    
    [super layoutSubviews];
    
    _button.frame = CGRectMake(self.bounds.size.width - 55, 15, 30, 30);
    _button.backgroundColor = [UIColor redColor];
    [_button setImage:[UIImage imageNamed:@"leguanMV64"] forState:UIControlStateNormal];
    [_button addTarget:self action:@selector(buttonAction:) forControlEvents:UIControlEventTouchUpInside];
    
    _myPregress.frame = CGRectMake(80, 30, self.bounds.size.width - 200, 10);
    _myPregress.backgroundColor = [UIColor cyanColor];
    
    _title.frame = CGRectMake(10, 0, 10, 20);
    [_title sizeToFit];
    
    _name.frame = CGRectMake(10, 30, 20, 15);
    _name.font = [UIFont systemFontOfSize:15];
    [_name sizeToFit];
    
    
}

- (void)receiveNotification:(NSNotification *)message {
    
    self.title.hidden = YES;
    self.name.hidden = YES;
    self.myPregress.hidden = YES;
    self.button.hidden = YES;
    
}

- (void)setDetailModel:(HZJSongDetailModel *)detailModel {
    
    _detailModel = detailModel;
    _title.text = detailModel.name;
    _name.text = detailModel.singerName;
    if (_detailModel.auditionList.count > 1) {
    _listModel = _detailModel.auditionList[1];

    _urlStr = _listModel.url;
    
    [self startDownload];
    } else {
        [[[UIAlertView alloc] initWithTitle:_title.text message:@"我们会努力争取的" delegate:self cancelButtonTitle:@"知道了" otherButtonTitles: nil] show];
    }
}

#pragma mark - 推荐界面的下载
- (void)setTuijianSongModel:(HZJSongListModel *)tuijianSongModel {
    _tuijianSongModel = tuijianSongModel;
    _title.text = tuijianSongModel.name;
    _name.text = tuijianSongModel.singerName;
    
    if (_tuijianSongModel.auditionList.count > 1) {
        _listModel = _detailModel.auditionList[1];
        
        _urlStr = _listModel.url;
        
        [self startDownload];
    } else {
        [[[UIAlertView alloc] initWithTitle:_title.text message:@"我们会努力争取的" delegate:self cancelButtonTitle:@"知道了" otherButtonTitles: nil] show];
    }
}

/**
 *  session的懒加载
 */
- (NSURLSession *)session
{
    if (nil == _session) {
        
        NSURLSessionConfiguration *cfg = [NSURLSessionConfiguration defaultSessionConfiguration];
        self.session = [NSURLSession sessionWithConfiguration:cfg delegate:self delegateQueue:[NSOperationQueue mainQueue]];
    }
    return _session;
}


- (void)buttonAction:(UIButton *)sender {
    NSLog(@"dafgdsg");
    // 按钮状态取反
    sender.selected = !sender.isSelected;
    
    if (nil == self.downloadTask) { // 开始（继续）下载
        if (self.resumeData) { // 继续下载
            [self resume];
        }else{ // 从0开始下载
            [self startDownload];
        }
        
    }else{ // 暂停
        [self pause];
    }
    
}

/**
 *  从0开始下载
 */
- (void)startDownload
{
    NSURL *url = [NSURL URLWithString:self.urlStr];
     // 创建任务
     self.downloadTask = [self.session downloadTaskWithURL:url];

 
    // 开始任务
    [self.downloadTask resume];
}

/**
 *  恢复下载
 */

- (void)resume
{
    // 传入上次暂停下载返回的数据，就可以恢复下载
    self.downloadTask = [self.session downloadTaskWithResumeData:self.resumeData];
    
    [self.downloadTask resume]; // 开始任务
    
    self.resumeData = nil;
}

/**
 *  暂停
 */
- (void)pause
{
    __weak typeof(self) selfVc = self;
    [self.downloadTask cancelByProducingResumeData:^(NSData *resumeData) {
        //  resumeData : 包含了继续下载的开始位置\下载的url
        selfVc.resumeData = resumeData;
        selfVc.downloadTask = nil;
    }];
}

#pragma mark -- NSURLSessionDownloadDelegate
/**
 *  下载完毕会调用
 *
 *  @param location     文件临时地址
 */
- (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask
didFinishDownloadingToURL:(NSURL *)location
{
//    NSString *caches = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject];
//    // response.suggestedFilename ： 建议使用的文件名，一般跟服务器端的文件名一致
//    NSString *file = [caches stringByAppendingPathComponent:downloadTask.response.suggestedFilename];
    

//    NSString *path = [NSHomeDirectory() stringByAppendingString:@"/Documents/music"];
    NSString *path = [NSString stringWithFormat:@"%@/music", FILEPATH];
    NSFileManager *fileManager = [NSFileManager defaultManager];
    [fileManager createDirectoryAtPath:path withIntermediateDirectories:YES attributes:nil error:nil];
    // response.suggestedFilename ： 建议使用的文件名，一般跟服务器端的文件名一致
    NSString *file = [path stringByAppendingPathComponent:[NSString stringWithFormat:@"%@-%@.mp3", _detailModel.name, _detailModel.singerName]];
    
    // 将临时文件剪切或者复制Caches文件夹
    NSFileManager *mgr = [NSFileManager defaultManager];
    
    // AtPath : 剪切前的文件路径
    // ToPath : 剪切后的文件路径
    [mgr moveItemAtPath:location.path toPath:file error:nil];
    
    NSLog(@"%@", file);
    // 提示下载完成
//    [[[UIAlertView alloc] initWithTitle:@"下载完成" message:downloadTask.response.suggestedFilename delegate:self cancelButtonTitle:@"知道了" otherButtonTitles: nil] show];
    self.title.hidden = YES;
    self.name.hidden = YES;
    self.myPregress.hidden = YES;
    self.button.hidden = YES;
    [self storage];
}

/**
 *  每次写入沙盒完毕调用
 *  在这里面监听下载进度，totalBytesWritten/totalBytesExpectedToWrite
 *
 *  @param bytesWritten              这次写入的大小
 *  @param totalBytesWritten         已经写入沙盒的大小
 *  @param totalBytesExpectedToWrite 文件总大小
 */
- (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask
      didWriteData:(int64_t)bytesWritten
 totalBytesWritten:(int64_t)totalBytesWritten
totalBytesExpectedToWrite:(int64_t)totalBytesExpectedToWrite
{
    self.myPregress.progress = (double)totalBytesWritten/totalBytesExpectedToWrite;
//    self.pgLable.text = [NSString stringWithFormat:@"下载进度:%f",(double)totalBytesWritten/totalBytesExpectedToWrite];
}

/**
 *  恢复下载后调用，
 */
- (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask
 didResumeAtOffset:(int64_t)fileOffset
expectedTotalBytes:(int64_t)expectedTotalBytes
{
    
}

- (void)storage {
    
//    NSFileManager * fileManager = [NSFileManager defaultManager];
//    NSArray * tempFileList = [[NSArray alloc] initWithArray:[fileManager contentsOfDirectoryAtPath:FILEPATH error:nil]];
//    //    NSLog(@"%@", tempFileList);
//    NSMutableArray *array = [NSMutableArray arrayWithCapacity:0];
//    
//    for (int i = 0; i < tempFileList.count; i++) {
//        if ([[tempFileList[i] pathExtension] isEqualToString:@"mp3"]) {
//            [array addObject:tempFileList[i]];
//        }
//    }
    
//    NSNotificationCenter *center = [NSNotificationCenter defaultCenter];
//    
//    [center postNotificationName:@"DOWNLOAD" object:array userInfo:nil];
    
}


/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect {
    // Drawing code
}
*/

@end
